package com.ruoyi.inducePest.service.device.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.inducePest.domain.ChangeRecord;
import com.ruoyi.inducePest.domain.device.*;
import com.ruoyi.inducePest.domain.inducePest.BeginTimeAndEndTimt;
import com.ruoyi.inducePest.domain.inducePest.InducePestImgInfo;
import com.ruoyi.inducePest.domain.inducePest.InducePestNumType;
import com.ruoyi.inducePest.domain.inducePest.SelectInducePestImgInfo;
import com.ruoyi.inducePest.mapper.ChangeRecordMapper;
import com.ruoyi.inducePest.mapper.device.DeviceBoardRecordMapper;
import com.ruoyi.inducePest.mapper.device.InduceDeviceMapper;
import com.ruoyi.inducePest.mapper.inducePest.InducePestDataAnalysisMapper;
import com.ruoyi.inducePest.mapper.inducePest.InducePestImgMapper;
import com.ruoyi.inducePest.service.device.InduceDeviceLureChangeRecordService;
import com.ruoyi.inducePest.service.device.InduceDeviceService;
import com.ruoyi.permission.Dao.SerDevicePermi;
import com.ruoyi.permission.mapper.SerDevicePermiMapper;
import com.ruoyi.utils.ImgDrawCircleTool;
import com.ruoyi.utils.LocationUtil;
import lombok.extern.slf4j.Slf4j;
import net.sourceforge.pinyin4j.PinyinHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: ruoyi_202130504106_李航
 * @description:
 * @author: LiHang
 * @create: 2022-04-11 10:12
 **/

@Slf4j
@Service
public class InduceDeviceServiceImpl implements InduceDeviceService {

    @Autowired
    private InduceDeviceMapper induceDeviceMapper;

    @Autowired
    private SerDevicePermiMapper devicePermiMapper;


    @Autowired
    private DeviceBoardRecordMapper deviceBoardRecordMapper;


    @Autowired
    private InducePestDataAnalysisMapper inducePestDataAnalysisMapper;

    @Autowired
    private InducePestImgMapper inducePestImgMapper;

    @Autowired
    private ChangeRecordMapper changeRecordMapper;
    @Autowired
    private InduceDeviceLureChangeRecordService induceDeviceLureChangeRecordService;
    /**
     * 存储文件的路径
     */
    @Value("${ruoyi.profile}")
    private String profile;

    @Override
    public String getDeviceNameByDeviceId(Integer deviceId){
        return induceDeviceMapper.selectDeviceNameByDeviceId(deviceId);
    }

    @Override
    public TableDataInfo selectAllDeviceInfo() {

        List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectAllDeviceInfo();

        return getTableDataInfo(induceDeviceInfos,null,null);
    }

    @Override
    public TableDataInfo selectDeviceInfoByCondition(InduceDeviceInfo induceDeviceInfo, List<SerDevicePermi> allDeviceInfos) {
        induceDeviceInfo.setUserId(null);
//        if(induceDeviceInfo.getUserId()==1){
//            induceDeviceInfo.setUserId(null);
//        }
        List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
        if(!allDeviceInfos.isEmpty()) {
            induceDeviceInfos = induceDeviceInfos.stream()
                    .filter(filteredinduceDeviceInfo -> allDeviceInfos.stream()
                            .anyMatch(allDeviceInfo -> allDeviceInfo.getDeviceNo().equals(filteredinduceDeviceInfo.getId())))
                    .collect(Collectors.toList());
        }

        return getTableDataInfo(induceDeviceInfos, induceDeviceInfo.getBeginTime(), induceDeviceInfo.getEndTime());
    }

    @Override
    public InduceDeviceInfo selectDeviceInfoByDeviceId(Integer deviceId) {
        InduceDeviceInfo induceDeviceInfo = new InduceDeviceInfo();
        induceDeviceInfo.setId(deviceId);
        List<InduceDeviceInfo> induceDeviceInfos = induceDeviceMapper.selectDeviceInfoByCondition(induceDeviceInfo);
        return induceDeviceInfos==null?null:induceDeviceInfos.get(0);
    }

    @Override
    public int insertDeviceInfo(InduceDeviceInfo induceDeviceInfo) {
        if(induceDeviceInfo.getLureUpdateDate()==null){
            induceDeviceInfo.setLureUpdateDate(new Date());
        }
        if(induceDeviceInfo.getIotCardTerm()==null){
            induceDeviceInfo.setIotCardTerm(new Date());
        }
        return induceDeviceMapper.insertDeviceInfo(induceDeviceInfo);
    }



    @Override
    public int updateDeviceInfoById(InduceDeviceInfo induceDeviceInfo) throws IOException {
        InduceDeviceInfo selectDevice = new InduceDeviceInfo();
        Integer id = induceDeviceInfo.getId();
        String manualId = induceDeviceInfo.getManualId();
        selectDevice.setId(id);
        insertRecord(induceDeviceInfo);
        InduceDeviceInfo originDevice = induceDeviceMapper.selectDeviceById(induceDeviceInfo.getId());
        if(originDevice==null){
            return 0;
        }
        //存储粘板的更新记录
        DeviceLureChangeRecord deviceLureChangeRecord = new DeviceLureChangeRecord();
        deviceLureChangeRecord.setLure(induceDeviceInfo.getLure());
        deviceLureChangeRecord.setIsChangeBoard(induceDeviceInfo.getBoardStatus());
        deviceLureChangeRecord.setLureValidityTime(induceDeviceInfo.getLureValidityTime());
        deviceLureChangeRecord.setDeviceId(induceDeviceInfo.getId());
        deviceLureChangeRecord.setLureUpdateDate(induceDeviceInfo.getLureUpdateDate());
        induceDeviceLureChangeRecordService.insertChangeRecord(deviceLureChangeRecord);
        //更新经纬度和位置信息
        if(induceDeviceInfo.getLocation()!=null && induceDeviceInfo.getLocation()!=""){
            double[] location = LocationUtil.geocode(induceDeviceInfo.getLocation());
            Double longitudeFinal = location[0];
            Double latitudeFinal = location[1];
            induceDeviceInfo.setLongitude(longitudeFinal);
            induceDeviceInfo.setLatitude(latitudeFinal);
            JSONObject locationObject = LocationUtil.reverseGeoCode(longitudeFinal,latitudeFinal);
            //详细地址，用于更新各个表中的地址
//            String locationStr = locationObject.getString("formattedAddress");
            String area = locationObject.getString("city");
            String province = locationObject.getString("province");
            if(devicePermiMapper.selectByDeviceSerial(originDevice.getCameraId()) != null){
                SerDevicePermi devicePermiInfo = devicePermiMapper.selectByDeviceSerial(originDevice.getCameraId());
                devicePermiInfo.setArea(area);
                devicePermiInfo.setProvince(province);
                devicePermiInfo.setLongitude(longitudeFinal);
                devicePermiInfo.setLatitude(latitudeFinal);
                devicePermiMapper.updateByPrimaryKeySelective(devicePermiInfo);
//                if(j > 0){
//                    return AjaxResult.success("更新权限设备的地区信息成功");
//                }else {
//                    return AjaxResult.error("更新权限设备的地区信息失败");
//                }
            }

        }

        //更新设备权限表信息
        String deviceSerial = induceDeviceMapper.selectDeviceById(induceDeviceInfo.getId()).getCameraId();
        if ((devicePermiMapper.selectByDeviceSerial(deviceSerial)) != null) {
            String deviceName = induceDeviceInfo.getName()==null?originDevice.getName():induceDeviceInfo.getName();
            String onlineState = originDevice.getStatus();
            SerDevicePermi devicePermiInfo = devicePermiMapper.selectByDeviceSerial(deviceSerial);
            devicePermiInfo.setDeviceName(deviceName).setOnlineState(onlineState).setManualId(manualId).setDeviceNo(id);
            devicePermiMapper.updateByPrimaryKeySelective(devicePermiInfo);
        }

        //根据性诱剂更新时间修改图片属性
        if(induceDeviceInfo.getLureUpdateDate()!=null){
            SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
            selectInducePestImgInfo.setBeginTime(induceDeviceInfo.getLureUpdateDate());
            selectInducePestImgInfo.setEndTime(new Date());
            selectInducePestImgInfo.setDeviceId(induceDeviceInfo.getId());
            selectInducePestImgInfo.setImgPest(induceDeviceInfo.getLure());
            inducePestImgMapper.updatePestByCondition(selectInducePestImgInfo);
            List<InducePestImgInfo> infoByConditionList = inducePestImgMapper.getInfoByCondition(selectInducePestImgInfo);
            ImgDrawCircleTool tool = new ImgDrawCircleTool();
            for (InducePestImgInfo inducePestImgInfo: infoByConditionList) {
                ObjectMapper objectMapper = new ObjectMapper();
                Map<String, Integer> insectMap = new HashMap<>();
                if(inducePestImgInfo.getTagManual()!=null){
                    insectMap = objectMapper.readValue(inducePestImgInfo.getTagManual(), new TypeReference<Map<String, Integer>>() {});
                }else{
                    insectMap = null;
                }

                int tagAllCount=getMapAllSum(insectMap);
                // 用来判断imgPest是否是模型能识别的，从而分别进行两种操作
                boolean flagForPestIsModel=false;
                Lure lure = new Lure();
                lure.setCanModel(1);
                List<Lure> lures = selectLure(lure);
                // 提取lure字段生成新的List
                List<String> induceModelPestList = lures.stream()
                        .map(Lure::getLure)
                        .collect(Collectors.toList());
                Integer tagPestCount=0;
                if(inducePestImgInfo.getImgPest()==null){
                    tagPestCount=0;
                }else if(induceModelPestList.contains(inducePestImgInfo.getImgPest())){
                    flagForPestIsModel=true;
                    tagPestCount=insectMap.get(getPinYinHeadChar(inducePestImgInfo.getImgPest()));
                    if(tagPestCount==null){
                        tagPestCount=0;
                    }
                }else {
                    tagPestCount=tagAllCount;
                }
//                Integer tagOtherCount=(tagAllCount-tagPestCount<0)?0:tagAllCount-tagPestCount;
//
//                String[] strArr = inducePestImgInfo.getCorner().split(",");
//
//                List<int[]> listCorner = new ArrayList<>();
//                int[] intArr = new int[4];
//
//                for (int i = 0; i < strArr.length; i++) {
//                    intArr[i % 4] = Integer.parseInt(strArr[i]);
//                    if ((i + 1) % 4 == 0) {
//                        listCorner.add(intArr);
//                        intArr = new int[4];
//                    }
//                }
//                String[] arr = inducePestImgInfo.getTagForDraw().split(",");
//                List<String> tagForDraw = Arrays.asList(arr);
//
//                String resultPath = tool.doDrawRectangle(listCorner,
//                        tagForDraw,
//                        profile + inducePestImgInfo.getUrl().replace("/profile",""), tagPestCount,tagOtherCount,inducePestImgInfo.getImgPest(),flagForPestIsModel).replace(profile, Constants.RESOURCE_PREFIX);
            }
        }

        //在没传性诱剂更新时间且更新性诱剂的情况下，性诱剂更新时间设为当前时间
        if(!originDevice.getLure().equals(induceDeviceInfo.getLure()) && induceDeviceInfo.getLureUpdateDate()==null){
            induceDeviceInfo.setLureUpdateDate(new Date());
        }
//        if((originDevice.getBoardUpdateDate()==null) || (!originDevice.getBoardUpdateDate().equals(induceDeviceInfo.getBoardUpdateDate()) && induceDeviceInfo.getBoardUpdateDate()!=null)){
//            DeviceBoardRecord deviceBoardRecord = new DeviceBoardRecord();
//            deviceBoardRecord.setBoardRecord(induceDeviceInfo.getBoardRecord());
//            deviceBoardRecord.setBoardUpdateDate(induceDeviceInfo.getBoardUpdateDate());
//            deviceBoardRecord.setDeviceId(induceDeviceInfo.getId());
//            deviceBoardRecord.setUpdateTime(new Date());
//            deviceBoardRecordMapper.insertDeviceBoardRecord(deviceBoardRecord);
//        }


        return induceDeviceMapper.updateDeviceInfoById(induceDeviceInfo);
    }

    @Override
    public List<DeviceTypeAndCount> selectDeviceTypeAndCount() {
        return induceDeviceMapper.selectDeviceTypeAndCount();
    }

    @Override
    public TableDataInfo selectDeviceBoardRecordByCondition(DeviceBoardRecord deviceBoardRecord, Integer pageNum, Integer pageSize) {
        if (StringUtils.isNotNull(pageNum) && StringUtils.isNotNull(pageSize)) {
            PageHelper.startPage(pageNum, pageSize);
        }
        List<DeviceBoardRecord> deviceBoardRecords = deviceBoardRecordMapper.selectBoardRecordByCondition(deviceBoardRecord);

        PageInfo<DeviceBoardRecord> pageInfo = new PageInfo<>(deviceBoardRecords);
        return getTableDataInfo(deviceBoardRecords,pageInfo);


    }

    @Override
    public List<String> selecAlltLure() {

        return induceDeviceMapper.selectAllLures();
    }

    @Override
    public int insertLure(Lure lure) {
        if(StringUtils.isEmpty(lure.getLure())){
            return 0;
        }
        lure.setAbbreviation(getPinYinHeadChar(lure.getLure()));
        return induceDeviceMapper.insertLure(lure);
    }

    @Override
    public int updateLure(Lure lure) {
        if(StringUtils.isEmpty(lure.getLure())){
            return 0;
        }
        lure.setAbbreviation(getPinYinHeadChar(lure.getLure()));
        return induceDeviceMapper.updateLure(lure);
    }

    @Override
    public int deleteLure(Lure lure) {
        return induceDeviceMapper.deleteLure(lure);
    }

    @Override
    public List<Lure> selectLure(Lure lure) {
        return induceDeviceMapper.selectLures(lure);
    }

    private TableDataInfo getTableDataInfo(List<DeviceBoardRecord> deviceBoardRecords, PageInfo<DeviceBoardRecord> pageInfo) {
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(deviceBoardRecords);
        rspData.setTotal(pageInfo.getTotal());
        return rspData;
    }

    private TableDataInfo getTableDataInfo(List<InduceDeviceInfo> induceDeviceInfos,  Date beginTime, Date endTime) {
        ArrayList<InduceDeviceInfo> returnInduceDeviceInfos = new ArrayList<>();
        for (InduceDeviceInfo induceDeviceInfo : induceDeviceInfos) {

            /**
             * 计算性诱剂剩余时间，截止日期等信息
             */
            Date lureUpdateDate = induceDeviceInfo.getLureUpdateDate();
            Integer lureValidityTime = induceDeviceInfo.getLureValidityTime();
            if(lureUpdateDate!=null && lureValidityTime!=null) {
                int daysPass = Math.abs((int) ((lureUpdateDate.getTime() - new Date().getTime()) / (1000 * 3600 * 24)));

                int daysRemaining = 0;
                if (daysPass >= lureValidityTime) {
                    daysRemaining = 0;
                } else {
                    daysRemaining = lureValidityTime - daysPass;
                }
                induceDeviceInfo.setLureDaysRemaining(daysRemaining);

                Calendar calendar = Calendar.getInstance();
                calendar.setTime(lureUpdateDate);
                calendar.add(Calendar.DATE, lureValidityTime);
                Date lureEndDays = calendar.getTime();
                induceDeviceInfo.setLureEndDays(lureEndDays);
            }



            /**
             * 计算设备是否提醒检查诱芯,1为提醒，0为不提醒
             */
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.set(Calendar.HOUR_OF_DAY, 0);
            calendar.set(Calendar.MINUTE, 0);
            calendar.set(Calendar.SECOND, 0);
            calendar.add(Calendar.DATE, -3);
            Date startTime = calendar.getTime();

            BeginTimeAndEndTimt beginTimeAndEndTimt = new BeginTimeAndEndTimt();
            beginTimeAndEndTimt.setBeginTime(startTime);
            beginTimeAndEndTimt.setEndTime(new Date());

            beginTimeAndEndTimt.setDeviceId(induceDeviceInfo.getId());
            List<InducePestImgInfo> inducePestImgInfos = inducePestDataAnalysisMapper.selectAllInfoByDayAndDevice(beginTimeAndEndTimt);
            InducePestNumType insectTypeRecord = new InducePestNumType();
            insectTypeRecord.setNc(0);
            insectTypeRecord.setDzjym(0);
            insectTypeRecord.setDm(0);
            insectTypeRecord.setCdtye(0);
            insectTypeRecord.setEhm(0);
            for (InducePestImgInfo inducePestImgInfo:inducePestImgInfos) {
                InducePestNumType insectType = new InducePestNumType();
                //今日图片里所有的害虫数量
                boolean isFirst=false;
                if(inducePestImgInfo.getTagManual()!=null ){
                    List<String> tagManualList=new ArrayList<String>();
                    tagManualList.add(inducePestImgInfo.getTagManual());
                    insectType=json2InsectType(tagManualList,isFirst);
                }else {
                    List<String> taglList=new ArrayList<String>();
                    taglList.add(inducePestImgInfo.getTag());
                    insectType = json2InsectType(taglList, isFirst);
                }
                insectTypeRecord.setNc(insectTypeRecord.getNc()+insectType.getNc());
                insectTypeRecord.setDzjym(insectTypeRecord.getDzjym()+insectType.getDzjym());
                insectTypeRecord.setDm(insectTypeRecord.getDm()+insectType.getDm());
                insectTypeRecord.setCdtye(insectTypeRecord.getCdtye()+insectType.getCdtye());
                insectTypeRecord.setEhm(insectTypeRecord.getEhm()+insectType.getEhm());
            }
            String maxPest="";
            int other=0;
            if(insectTypeRecord.getNc()!=null){
                other=insectTypeRecord.getNc();
            }
            int dm=0;
            if(insectTypeRecord.getDm()!=null){
                dm=insectTypeRecord.getDm();
            }
            int cdtye=0;
            if(insectTypeRecord.getCdtye()!=null){
                cdtye=insectTypeRecord.getCdtye();
            }
            int dzjym=0;
            if(insectTypeRecord.getDzjym()!=null){
                dzjym=insectTypeRecord.getDzjym();
            }
            int ehm=0;
            if(insectTypeRecord.getEhm()!=null){
                ehm=insectTypeRecord.getEhm();
            }
            int all[]=new int[5];
            all[0]=other;
            all[1]=dzjym;
            all[2]=dm;
            all[3]=cdtye;
            all[4]=ehm;
            int max = getMax(all);
            String lure= induceDeviceInfo.getLure();
            if(lure==null){
                induceDeviceInfo.setIsRemindLurReplace(0);
            }else {
                if (lure.contains("草地贪夜蛾") && max != cdtye) {
                    induceDeviceInfo.setIsRemindLurReplace(1);
                } else if (lure.contains("稻纵卷叶螟") && max != dzjym) {
                    induceDeviceInfo.setIsRemindLurReplace(1);
                } else if (lure.contains("大螟") && max != dm) {
                    induceDeviceInfo.setIsRemindLurReplace(1);
                } else if (lure.contains("二化螟") && max != ehm) {
                    induceDeviceInfo.setIsRemindLurReplace(1);
                } else {
                    induceDeviceInfo.setIsRemindLurReplace(0);
                }
            }

            /**
             * 获取指定时间内该设备所拍摄过的害虫类别
             */
            SelectInducePestImgInfo selectInducePestImgInfo = new SelectInducePestImgInfo();
            selectInducePestImgInfo.setDeviceId(induceDeviceInfo.getId());
            if(beginTime!=null) {
                selectInducePestImgInfo.setBeginTime(beginTime);
            }
            if(endTime!=null) {
                calendar.setTime(endTime);

            }else if(beginTime!=null){
                endTime=new Date();
            }
            calendar.set(Calendar.HOUR_OF_DAY, 23);
            calendar.set(Calendar.MINUTE, 59);
            calendar.set(Calendar.SECOND, 59);
            endTime = calendar.getTime();
            selectInducePestImgInfo.setEndTime(endTime);
            List<String> imgPestType = inducePestImgMapper.selectImgPestByDeviceId(selectInducePestImgInfo);


            List<String> newImgPestType = new ArrayList<String>();
            for (String str : imgPestType) {
                if (!newImgPestType.contains(str)) {
                    newImgPestType.add(str);
                }
            }

            induceDeviceInfo.setPestType(newImgPestType);

            /**
             * 根据用户设备状态判断电量
             * 在线即为100，离线即为0
             */
            if("离线".equals(induceDeviceInfo.getStatus())){
                induceDeviceInfo.setBatteryMargin("0");

            }else {
                induceDeviceInfo.setBatteryMargin("100");
            }

            returnInduceDeviceInfos.add(induceDeviceInfo);

        }

        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setRows(returnInduceDeviceInfos);

        rspData.setTotal(returnInduceDeviceInfos.size());

        return rspData;
    }

    /**
     * 记录修改值
     * @param newInduceDeviceInfo
     * @return
     */
    public void insertRecord(InduceDeviceInfo newInduceDeviceInfo) {
        ChangeRecord changeRecord = new ChangeRecord();
        changeRecord.setChangeTable("ser_induce_device_info");
        changeRecord.setUpdateTime(new Date());
        changeRecord.setChangeInfoId(newInduceDeviceInfo.getId());
        InduceDeviceInfo oldDevice = induceDeviceMapper.selectDeviceById(newInduceDeviceInfo.getId());
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        changeRecord.setUserId(Integer.valueOf(userId.intValue()));
        try{
            //通过getDeclaredFields()⽅法获取对象类中的所有属性（含私有）
            Field[] newFields = newInduceDeviceInfo.getClass().getDeclaredFields();
            for (Field newField : newFields) {
                //设置允许通过反射访问私有变量
                newField.setAccessible(true);
                //获取字段属性名称
                String name = newField.getName();
                if(name.equals("id")){
                    continue;
                }
                if(newField.get(newInduceDeviceInfo)!=null && newField.get(newInduceDeviceInfo).toString().length()!=0){
                    changeRecord.setChangeKey(name);
                    //获取字段的值

                    String value = newField.get(newInduceDeviceInfo).toString();
                    changeRecord.setChangeNewValue(value);
                    Field[] oldFields = oldDevice.getClass().getDeclaredFields();
                    for (Field oldField : oldFields) {
                        oldField.setAccessible(true);
                        if(oldField.getName().equals(name)){
                            if(oldField.get(oldDevice)==null){
                                changeRecord.setChangeOldValue(null);
                            }else {
                                changeRecord.setChangeOldValue(oldField.get(oldDevice).toString());
                            }
                            break;
                        }
                    }
                    if(changeRecord.getChangeNewValue().equals(changeRecord.getChangeOldValue())){
                        continue;
                    }
                    changeRecordMapper.insertChangeInfo(changeRecord);
                }
                //其他⾃定义操作
            }
        }
        catch (Exception ex){
            //处理异常
        }

    }

    /**
     * 获取数组中的最大值
     * @param array
     * @return
     */
    public static int getMax (int [] array) {
        int max = array[0]; //局部变量写在方法内部
        for (int i = 1; i < array.length; i++) {
            if (array[i] > max ) {
                max = array[i];
            }
        }
        return max;
    }

    /**
     * 将数据库中的JSON格式转换为对象格式
     * other : 0,
     * 'dm': 1,
     * 'ehm': 2,
     * 'dzjym': 3,
     * 'cdtye': 4,
     *
     * @param list list列表
     * @return InsectType类型
     */
    public static InducePestNumType json2InsectType(List<String> list, boolean isFirst) {

        int dm = 0;

        int ehm = 0;

        int dzjym = 0;

        int cdtye = 0;

        int other = 0;

        int ymm=0;



        for (String s : list) {
            if (s != null && s.length()!=0) {
                JSONObject totalNum = JSON.parseObject(s);
                if (totalNum.containsKey("1")) {
                    dm += (Integer) totalNum.get("1");
                }
                if (totalNum.containsKey("2")) {
                    ehm += (Integer) totalNum.get("2");
                }
                if (totalNum.containsKey("ehm")) {
                    ehm += (Integer) totalNum.get("ehm");
                }
                if (totalNum.containsKey("3")) {
                    dzjym += (Integer) totalNum.get("3");
                }
                if (totalNum.containsKey("dzjym")) {
                    dzjym += (Integer) totalNum.get("dzjym");
                }
                if (totalNum.containsKey("4")) {
                    cdtye += (Integer) totalNum.get("4");
                }
                if (totalNum.containsKey("cdtye")) {
                    cdtye += (Integer) totalNum.get("cdtye");
                }
                if (totalNum.containsKey("ymm")) {
                    ymm += (Integer) totalNum.get("ymm");
                }


                if (totalNum.containsKey("0")) {
                    other += (Integer) totalNum.get("0");
                }
                if(isFirst){
                    break;
                }
            }
        }
        return new InducePestNumType(dm, ehm, dzjym, cdtye, ymm,other);
    }

    /**
     * 得到中文首字母
     *
     * @param str
     * @return
     */
    public static String getPinYinHeadChar(String str) {

        String convert = "";
        for (int j = 0; j < str.length(); j++) {
            char word = str.charAt(j);
            String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);
            if (pinyinArray != null) {
                convert += pinyinArray[0].charAt(0);
            } else {
                convert += word;
            }
        }
        convert = convert.replaceAll("[^A-Z^a-z^0-9]", "");
        return convert;
    }

    /**
     * 计算map中的虫子总数
     * @param insectMap
     * @return
     */
    public Integer getMapAllSum(Map<String, Integer> insectMap){
        if(insectMap==null){
            return 0;
        }
        int totalQuantity = 0;
        for (int quantity : insectMap.values()) {
            if(quantity<0){
                continue;
            }
            totalQuantity += quantity;
        }
        return totalQuantity;
    }



}
